package com.qidian.client;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;

import org.apache.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

/**
 * 从360取题
 * 
 * */
public class ThreadFetchMsg extends Thread
{
	static Logger logger = Logger.getLogger(ThreadFetchMsg.class) ;
    protected boolean      isStopped    = false;
    protected Thread       runningThread= null;
    
	static int timeOut = 10 ;
	static int fetchSize = 1 ;
	static TransMessageBeanCache tMsgCache = TransMessageBeanCache.getInstance() ;
	JSONParser parser = new JSONParser() ;
	int clientId = 1 ;
	int transType = 1 ;
	String password ;
	
	public ThreadFetchMsg(int clientId, int transType, String password)
	{
		this.clientId = clientId ;
		this.transType = transType ;
		this.password = password ;
	}
	
	// 从360取题，放入转发消息缓冲区
	public void run()
	{
        synchronized(this){
            this.runningThread = Thread.currentThread();
        }
		
        System.out.println(this.getClass().getName() + " start up for "+ TransConstants.serverURL) ;
        System.out.println("clientId:"+ clientId+", transType: "+transType + ", password:"+ password);
        
		GetMethod httpGet  = null ;
        
		while(!isStopped)
		{
			try
			{
				String url = TransConstants.serverURL+"/client?actionType=getTransMsg&clientId=" 
				+clientId + "&msgCount=" + fetchSize
				+"&transType="+ transType
				+"&password="+password
				+ "&_="+System.currentTimeMillis() ;
		        httpGet = new GetMethod(url) ;
		        httpGet.addRequestHeader("Cache", "no-cache") ;
	           int status = TransConstants.client.executeMethod(httpGet);
	           if (status != HttpStatus.SC_OK) 
	           {
	        	   logger.error("服务器访问异常:"+status);
	           }
	           else
	           {
	        	  String response = httpGet.getResponseBodyAsString() ;
	        	  if (response.charAt(0) == '-')
	        	  {
	        		  System.out.println(response) ;
	        		  logger.error("获取转发题目异常:"+response) ;
	        	  }
	        	  else
	        	  {
	        		  JSONArray msgsInfo = (JSONArray) parser.parse(response) ;
	    			  JSONObject jsonObj = (JSONObject)msgsInfo.get(0) ;
	    			  JSONArray msgs = (JSONArray)jsonObj.get("msg");

	    			  for(int i = 0 ; i < msgs.size(); i ++)
	    			  {
	    				  JSONObject msg = (JSONObject)msgs.get(i) ;
	    				  TransMessageBean msgBean = toTransMessageBean(msg) ;
	    				  
	    				  int fileSize = getFile(TransConstants.client,msgBean.getId(),msgBean.getFilePath()); 
	    				  if (fileSize > 0)
	    				  {
	    					  tMsgCache.addTrans(msgBean);
	    					  logger.info("取题:"+msgBean) ;
	    				  }
	    				  else
	    					  logger.error("下载文件失败:"+msgBean) ;
	    				  
		    			  Thread.sleep(200) ;
	    			  }
	    			  if (msgs.size() == 0)
	    			  {
	    				  Thread.sleep(500) ;
	    				  continue ;
	    			  }
	        	  }
	           }
	           
	           Thread.sleep(2000) ;
			}
			catch (Exception e) 
			{
	    	   logger.error("获取转发消息失败:"+e.getMessage()) ;
			}
			finally{
				httpGet.releaseConnection() ;
			}
		}
 	   	logger.info("Fetch msg thread stopped");
 	   	
	}
	/**
	 * 下载转发文件，
	 * 成功返回文件大小，失败返回-1
	 * @throws IOException 
	 * @throws HttpException 
	 * 
	 * */
	private int getFile(HttpClient client, String msgId, String filePath) throws HttpException, IOException
	{
		String url = TransConstants.serverURL+"/file?actionType=getFile&msgId=" + msgId;
		GetMethod getMethod = new GetMethod(url) ;
		
		
		int status = client.executeMethod(getMethod) ;
		if (status != HttpStatus.SC_OK)
			return -1 ;
		File file = new File(filePath);
		if (!file.exists())
		{
			file.createNewFile() ;
		}
		FileOutputStream fos = new FileOutputStream(file) ;
		InputStream is = getMethod.getResponseBodyAsStream() ;
		byte[] buf = new byte[1024] ;
		int totalSize = 0 , readSize = 0 ;
		while(true)
		{
			readSize = is.read(buf) ;
			if (readSize == -1)
				break;
			fos.write(buf,0,readSize) ;
			totalSize += readSize ;
		}
		is.close() ;
		fos.close() ;
		return totalSize ;
	}
	public TransMessageBean toTransMessageBean(JSONObject jsonObj)
	{
		TransMessageBean msg =  new TransMessageBean() ;
		
		String msgId = jsonObj.get("msgId").toString() ;
		Long interval = (Long)jsonObj.get("interval") ;
		Long recvTime = (Long)jsonObj.get("recvTime") ;
		String contentType = (String)jsonObj.get("contentType") ;
		// 如果是null,设置为jpg
		if (contentType == null || "null".equalsIgnoreCase(contentType))
			contentType = "jpg" ;
		Long gameType = (Long)jsonObj.get("gameType");
		
		msg.setId(msgId) ;
		msg.setInterval(interval.intValue()) ;
		msg.setReceiveTime(recvTime) ;
		msg.setContentType(contentType) ;
		msg.setGameType(gameType.intValue()) ;
		
		String filePath = TransConstants.dirTemp + "/" + msgId + "." + contentType ;
		msg.setFilePath(filePath) ;
		
		return msg ;
	}
	
	public static void main(String []args)
	{
		GetMethod ss = new GetMethod() ;
		NameValuePair[] paras = new NameValuePair[2] ;
		paras[0] = new NameValuePair("actionType","getFile") ;
		paras[1] = new NameValuePair("msgId","123") ;
		ss.setQueryString(paras) ;
		System.out.println(ss.getQueryString()) ;
		paras[1] = new NameValuePair("msgId","1234") ;
		ss.setQueryString(paras) ;
		System.out.println(ss.getQueryString()) ;
		return ;
	}
	
}
